<?php
class DomainModel {
	public function add($aInfo) {
		$iId = Base::$oBase->Db_insert ( 'domains', $aInfo );
		$this->_addItem ( $iId, $aInfo ['newkey'], $aInfo ['newvalue'], $aInfo ['newsort'] );
		return $iId;
	}
	
	public function edit($aInfo) {
		Base::$oBase->Db_update ( 'domains', $aInfo );
		$this->_replaceItem ( $aInfo ['id'], $aInfo ['key'], $aInfo ['value'], $aInfo ['sort'] );
		$this->_addItem ( $aInfo ['id'], $aInfo ['newkey'], $aInfo ['newvalue'], $aInfo ['newsort'] );
	}
	
	public function del($iId) {
		Base::$oBase->Db_del ( 'domains', array ('parent_id' => $iId ) );
		Base::$oBase->Db_del ( 'domains', array ('id' => $iId ) );
	}
	
	private function _addItem($iId, $aKey, $aValue, $aSort) {
		foreach ( $aKey as $iKey => $sRow ) {
			if ($sRow) {
				$aInfo = array ('parent_id' => $iId );
				$aInfo ['name'] = $sRow;
				$aInfo ['value'] = $aValue [$iKey];
				$aInfo ['sort'] = intval ( $aValue [$iKey] );
				Base::$oBase->Db_insert ( 'domains', $aInfo );
			}
		}
	}
	
	private function _replaceItem($iId, $aKey, $aValue, $aSort) {
		$aData = Base::$oBase->Db_ls ( 'domains', array ('parent_id' => $iId ), null, array ('sort' ) );
		foreach ( $aData ['item'] as $aRow ) {
			if (array_key_exists ( $aRow ['id'], $aKey )) {
				$aRow ['name'] = $aKey [$aRow ['id']];
				$aRow ['value'] = $aValue [$aRow ['id']];
				$aRow ['sort'] = $aSort [$aRow ['id']];
				Base::$oBase->Db_update ( 'domains', $aRow );
			} else {
				Base::$oBase->Db_del ( 'domains', array ('id' => $aRow ['id'] ) );
			}
		}
	}
	
	public function getList() {
		return Base::$oBase->Db_ls ( 'domains', array ('parent_id' => 0 ), null, array ('name' ) );
	}
	
	public function get($iId) {
		$aInfo = Base::$oBase->Db_get ( 'domains', array ('id' => $iId ) );
		$aData = Base::$oBase->Db_ls ( 'domains', array ('parent_id' => $iId ), null, array ('sort' ) );
		$aInfo ['item'] = $aData ['item'];
		return $aInfo;
	}
	
	public function getArray() {
		return Base::$oBase->Db_getArray ( 'domains', 'id', 'name', array ('parent_id' => 0 ) );
	}
}